package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.PaperMapper;
import com.hbnu.system.mapper.PaperQualificationMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.entity.*;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class PaperQualificationServiceImpl extends ServiceImpl<PaperQualificationMapper, Paper_Qualification> implements IPaperQualificationService {
    @Autowired
    private IPaperService iPaperService;

    @Autowired
    private IPaperTypeService iPaperTypeService;

    @Autowired
    private IPatentTypeService iPatentTypeService;

    @Autowired
    private PaperQualificationMapper paperQualificationMapper;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private IPaperauthorService iPaperauthorService;

    /**
     * 添加论文量化分数
     * @param paper_qualification
     * @return
     */
    @Override
    public boolean addPaper_Qualification(Paper_Qualification paper_qualification) {
        System.out.println(paper_qualification);
        Paper paper = iPaperService.getPaper(paper_qualification.getPaperID());
//        Paper checkPaper = BeanUtil.copyProperties(paper, Paper.class);
        if(Objects.isNull(paper)){
            throw new BaseException("论文编号有误!");
        }
        System.out.println("check="+paper.getStatus());
        checkRoleUtil.checkPermissionAchievement(paper.getStatus());

        if(Objects.isNull(paper)){
            throw new BaseException("论文编号有误!");
        }
        if(Objects.nonNull(this.getOne(Wrappers.lambdaQuery(Paper_Qualification.class)
                .eq(Paper_Qualification::getPaperID,paper_qualification.getPaperID())))){
            throw new BaseException("已经存在量化数据!");
        }
        if(String.valueOf(paper_qualification.getType1ID()).equals("")){
            throw new BaseException("请完整填写数据!");
        }
        if (String.valueOf((paper_qualification.getType2ID())).equals("")){
            throw new BaseException("请完整填写数据!");
        }
        if (String.valueOf((paper_qualification.getType3ID())).equals("")){
            throw new BaseException("请完整填写数据!");
        }

        if("true".equals(paper_qualification.getManualScoreMode())){
            paper.setScore(paper_qualification.getFinalValue());
            paper_qualification.setFinalValue(paper_qualification.getFinalValue());
            paper_qualification.setNote(paper_qualification.getNote());
        }else {
            Paper_Type paper_type = iPaperTypeService.getOne(Wrappers.lambdaQuery(Paper_Type.class)
                    .eq(Paper_Type::getType1ID, paper_qualification.getType1ID())
                    .eq(Paper_Type::getType2ID, paper_qualification.getType2ID())
                    .eq(Paper_Type::getType3ID, paper_qualification.getType3ID()));

            float value = paper_type.getValue();

            paper.setScore(value);

            paper_qualification.setFinalValue(value);
            paper_qualification.setPaperType1(paper_type.getPaperType1());
            paper_qualification.setPaperType2(paper_type.getPaperType2());
            paper_qualification.setPaperType3(paper_type.getPaperType3());
        }

        iPaperService.updatePaper(paper);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String paperid=paper_qualification.getPaperID();
        List<Paperauthor> paperauthorList = iPaperauthorService.listAuthor(paperid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (paperauthorList != null && !paperauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (paperauthorList.size() == 1) {
                Paperauthor soleAuthor = paperauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Paperauthor author : paperauthorList) {
                    iPaperauthorService.updatePaperAuthor(author);
                }
            }
        }
        
        return baseMapper.insert(paper_qualification) == 1;
    }

    /**
     * 删除论文量化分数
     * @param PaperQuantificationID
     * @return
     */
    @Override
    public boolean deletePaper_Qualification(String PaperQuantificationID) {

        Paper_Qualification paper_qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Paper_Qualification.class)
                .eq(Paper_Qualification::getPaperQuantificationID, PaperQuantificationID));
        Paper p1=iPaperService.getPaper(paper_qualification.getPaperID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        if (Objects.isNull(paper_qualification)){
            throw new BaseException("量化编号有误");
        }

        Paper paper = iPaperService.getPaper(paper_qualification.getPaperID());

        paper.setScore(0);

//        Paper paper = new Paper();
//        BeanUtils.copyProperties(paper,paper);
        iPaperService.updatePaper(paper);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String paperid=paper_qualification.getPaperID();
        List<Paperauthor> paperauthorList = iPaperauthorService.listAuthor(paperid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (paperauthorList != null && !paperauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (paperauthorList.size() == 1) {
                Paperauthor soleAuthor = paperauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Paperauthor author : paperauthorList) {
                    iPaperauthorService.updatePaperAuthor(author);
                }
            }
        }


        return baseMapper.deleteById(PaperQuantificationID) == 1;
    }


    /**
     * 查询单个论文的量化分数
     * @param PaperID
     * @return
     */
    @Override
    public List<Paper_Qualification> getOnePaper_Qualification(String PaperID) {
        Paper paper = iPaperService.query().eq("PaperID", PaperID).one();
        if(Objects.isNull(paper)){
            throw new BaseException("论文编号有误!");
        }

        List<Paper_Qualification> paper_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Paper_Qualification.class)
                .eq(Paper_Qualification::getPaperID, PaperID));
        return paper_qualifications;
    }

    /**
     * 更新论文分数
     * @param paper_qualification
     * @return
     */
    @Override
    public boolean upPaperScore(Paper_Qualification paper_qualification){
        Paper p1=iPaperService.getPaper(paper_qualification.getPaperID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        Paper_Qualification p=baseMapper.selectOne(Wrappers.lambdaQuery(Paper_Qualification.class)
                .eq(Paper_Qualification::getPaperQuantificationID,paper_qualification.getPaperQuantificationID()));
        p.setFinalValue(paper_qualification.getFinalValue());
        
        //更新paper表的论文分数
        Paper paper=paperMapper.selectOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperID,paper_qualification.getPaperID()));
        paper.setScore(paper_qualification.getFinalValue());
        
        // 先更新Paper表
        boolean paperUpdated = iPaperService.updateById(paper);
        // 再更新量化表
        boolean qualificationUpdated = baseMapper.updateById(p) == 1;

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String paperid=paper_qualification.getPaperID();
        List<Paperauthor> paperauthorList = iPaperauthorService.listAuthor(paperid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (paperauthorList != null && !paperauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (paperauthorList.size() == 1) {
                Paperauthor soleAuthor = paperauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Paperauthor author : paperauthorList) {
                    iPaperauthorService.updatePaperAuthor(author);
                }
            }
        }

        return paperUpdated && qualificationUpdated;
    }

    /**
     * 批量同步量化分数到论文表
     * @return 同步成功的记录数
     */
    @Override
    public int syncAllPaperScores() {
        // 1. 查询所有的量化数据
        List<Paper_Qualification> allQualifications = baseMapper.selectList(null);
        
        if (allQualifications == null || allQualifications.isEmpty()) {
            return 0;
        }
        
        int successCount = 0;
        
        // 2. 遍历每个量化数据，更新对应的论文分数
        for (Paper_Qualification qualification : allQualifications) {
            try {
                // 查询论文
                Paper paper = paperMapper.selectOne(Wrappers.lambdaQuery(Paper.class)
                        .eq(Paper::getPaperID, qualification.getPaperID()));
                
                if (paper != null) {
                    // 更新论文分数
                    paper.setScore(qualification.getFinalValue());
                    boolean updated = iPaperService.updateById(paper);
                    
                    if (updated) {
                        successCount++;
                        System.out.println("同步论文 " + paper.getPaperID() + " 分数: " + qualification.getFinalValue());
                    }
                }
            } catch (Exception e) {
                System.err.println("同步论文 " + qualification.getPaperID() + " 分数失败: " + e.getMessage());
            }
        }
        
        System.out.println("批量同步完成，总计: " + allQualifications.size() + " 条，成功: " + successCount + " 条");
        return successCount;
    }


}
